package fr.mmt.gisfizz.handler;

import fr.mmt.gisfizz.entity.User;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
public class LoginHandler {

    @Resource
    private UserDetailsService userDetailsService;

    /**
     * Check who is connected.
     *
     * @param request
     * @param response
     * @return
     * @throws java.io.IOException exception
     */
    @RequestMapping(value = "/remoteUser", method = RequestMethod.GET)
    public @ResponseBody
    UserDetails remoteUser(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {
        String login = request.getRemoteUser();
        log.debug("Remote user: {}", login);
        if (StringUtils.isBlank(login)) {
            return null;
        }
        return userDetailsService.loadUserByUsername(login);
    }

    /**
     * Login.
     *
     * @param request
     * @param response
     * @return user details
     * @throws java.io.IOException exception
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public @ResponseBody
    UserDetails login(final HttpServletRequest request, final HttpServletResponse response, @RequestBody User user) throws ServletException {
        log.debug("Login");
        request.login(user.getLogin(), user.getPassword());
        log.debug("Authentification success with remote user: {}", user.getLogin());
        return (User) userDetailsService.loadUserByUsername(user.getLogin());
    }

    /**
     * Logout.
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public @ResponseBody
    void logout(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {
        log.debug("Logout");
        request.logout();
    }
}
